<template>
  <div class="feedback-container">
    <!-- 评价分类筛选和总评分 -->
    <div class="filter-header">
      <div class="average-rating">
        我的信用分: <span class="rating-value">{{ userCredit }}</span>
      </div>
      <div class="filter-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="全部评价" name="all"></el-tab-pane>
          <el-tab-pane label="好评" name="good"></el-tab-pane>
          <el-tab-pane label="中评" name="medium"></el-tab-pane>
          <el-tab-pane label="差评" name="bad"></el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 评价列表 -->
    <div class="comment-list">
      <el-card 
        v-for="comment in comments.results" 
        :key="comment.id" 
        class="comment-card" 
        @click="showCommentDetail(comment.id)"
      >
        <div class="comment-header">
          <el-avatar :size="40" :src="comment.buyer_avatar || ''">
            {{ comment.buyer_username.charAt(0) }}
          </el-avatar>
          <div class="user-info">
            <div class="username">{{ comment.buyer_username }}</div>
            <div class="credit-score" v-if="comment.buyer_credit">
              信用分: {{ comment.buyer_credit }}
            </div>
          </div>
          <div class="comment-meta">
            <div class="rating-display">{{ comment.rating_display }}</div>
            <div class="date">{{ formatDate(comment.review_time) }}</div>
            <div class="order-code">订单号: {{ comment.order_code }}</div>
          </div>
        </div>
        <div class="comment-content">
          {{ comment.content }}
        </div>
        <div class="comment-footer">
          <div class="tags">
            <el-tag 
              v-if="comment.rating >= 4" 
              type="success" 
              size="small"
            >
              好评
            </el-tag>
            <el-tag 
              v-else-if="comment.rating === 3" 
              type="warning" 
              size="small"
            >
              中评
            </el-tag>
            <el-tag 
              v-else 
              type="danger" 
              size="small"
            >
              差评
            </el-tag>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty v-if="comments.results.length === 0" description="暂无评价"></el-empty>
    </div>

    <!-- 分页组件 -->
    <div class="pagination" v-if="comments.count > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="comments.count"
      ></el-pagination>
    </div>

    <!-- 评价详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评价详情"
      width="50%"
      :before-close="handleClose"
    >
      <div v-if="currentComment" class="comment-detail">
        <div class="detail-header">
          <el-avatar :size="60" :src="currentComment.buyer_avatar || ''">
            {{ currentComment.buyer_username.charAt(0) }}
          </el-avatar>
          <div class="detail-user-info">
            <h3>{{ currentComment.buyer_username }}</h3>
            <div class="detail-meta">
              <div class="detail-rating">
                <el-rate
                  v-model="currentComment.rating"
                  disabled
                  show-text
                  :texts="['很差', '较差', '一般', '不错', '很棒']"
                />
              </div>
              <div class="detail-date">
                {{ formatDate(currentComment.review_time) }}
              </div>
              <div class="detail-order-code">
                订单号: {{ currentComment.order_code }}
              </div>
            </div>
          </div>
        </div>
        <div class="detail-content">
          {{ currentComment.content }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import apiClient from '../../utils/request'

const router = useRouter()

// 评价数据
const comments = ref({ 
  results: [], 
  count: 0 
})

// 所有评价数据（用于计算总平均分）
const userCredit = ref('0.0')
// 当前查看的评价详情
const currentComment = ref(null)
const detailDialogVisible = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const activeTab = ref('all')
// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 获取用户信用分
const fetchUserCredit = async () => {
  try {
    const response = await apiClient.get('/api/users/user-info/')
    userCredit.value = response.data.credit_score
  } catch (error) {
    console.error('获取用户信用分失败:', error)
    ElMessage.error('获取信用分失败')
  }
}


// 获取评价数据（分页）
// 获取评价数据（分页）
const fetchComments = async (page = 1, size = 10, ratingFilter = null) => {
  try {
    const params = {
      page,
      page_size: size
    };

    // 添加评分过滤参数
    if (ratingFilter) {
      params.rating = ratingFilter;
    }

    // 获取用户信用分
    await fetchUserCredit();
    
    const response = await apiClient.get('/api/orders/reviews/', { 
      params,
    });

    // 不需要手动过滤评分，因为已经通过 API 参数过滤
    comments.value = {
      ...response.data,
      results: response.data.results,
      count: response.data.count
    };
  } catch (error) {
    ElMessage.error('获取评价失败');
    console.error('API错误:', error.response || error);
  }
};

// 获取单个评价详情
const fetchCommentDetail = async (id) => {
  try {
    const response = await apiClient.get(`/api/orders/reviews/${id}/`);
    
    currentComment.value = {
      ...response.data,
    };
  } catch (error) {
    ElMessage.error('获取评价详情失败');
    console.error('API错误:', error.response || error);
  }
};

// 显示评价详情
const showCommentDetail = async (id) => {
  await fetchCommentDetail(id);
  detailDialogVisible.value = true;
};

// 标签切换处理
const handleTabChange = () => {
  currentPage.value = 1;
  let ratingFilter = null;
  
  // 设置API过滤参数
  switch (activeTab.value) {
    case 'good':
      ratingFilter = '4,5'; // 好评
      break;
    case 'medium':
      ratingFilter = '3'; // 中评
      break;
    case 'bad':
      ratingFilter = '1,2'; // 差评
      break;
    default:
      ratingFilter = null; // 全部
  }
  
  fetchComments(currentPage.value, pageSize.value, ratingFilter);
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchComments(currentPage.value, newSize);
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchComments(newPage, pageSize.value);
}

// 关闭弹窗
const handleClose = () => {
  detailDialogVisible.value = false;
}

onMounted(
  async () => {
  if (!localStorage.getItem('access_token')) {
    router.push('/login')
    return
  }
  await fetchComments();
});
</script>

<style scoped lang="scss">
.feedback-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .average-rating {
    font-size: 18px;
    font-weight: 500;
    
    .rating-value {
      color: #f56c6c;
      font-weight: bold;
      font-size: 24px;
    }
  }
}

.filter-tabs {
  flex-grow: 1;
  margin-left: 20px;
}

.comment-list {
  display: grid;
  gap: 15px;
}

.comment-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  
  .el-avatar {
    flex-shrink: 0;
    margin-right: 15px;
  }
  
  .user-info {
    flex: 1;
    
    .username {
      font-weight: 600;
      font-size: 16px;
      margin-bottom: 5px;
    }
    
    .credit-score {
      font-size: 12px;
      color: #666;
    }
  }
  
  .comment-meta {
    text-align: right;
    
    .rating-display {
      font-size: 16px;
      font-weight: bold;
      color: #f56c6c;
      margin-bottom: 5px;
    }
    
    .date {
      color: #999;
      font-size: 13px;
    }
    
    .order-code {
      color: #666;
      font-size: 13px;
      margin-top: 5px;
    }
  }
}

.comment-content {
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
  padding: 0 10px;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
  
  .tags {
    .el-tag {
      margin-right: 5px;
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.comment-detail {
  padding: 10px;
  
  .detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .el-avatar {
      margin-right: 20px;
    }
    
    .detail-user-info {
      flex: 1;
      
      h3 {
        margin: 0 0 10px 0;
        font-size: 20px;
      }
    }
    
    .detail-meta {
      .detail-rating {
        margin-bottom: 10px;
      }
      
      .detail-date, .detail-order-code {
        color: #666;
        font-size: 14px;
        margin-top: 5px;
      }
    }
  }
  
  .detail-content {
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 4px;
    line-height: 1.8;
    font-size: 16px;
  }
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #f0f0f0;
}
</style>